# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
#============================================================================
# Copyright (C) 2005 Mike Wray <mike.wray@hp.com>
+# Copyright (C) 2005 XenSource Ltd.
#============================================================================
import sys
self.server = server
self.buffer_n = 1024
self.thread = None
- self.connected = True
- protocol.setTransport(self)
- protocol.connectionMade(addr)
+ self.protocol.setTransport(self)
def run(self):
self.thread = threading.Thread(target=self.main)
- #self.thread.setDaemon(True)
self.thread.start()
def main(self):
return True
def dataReceived(self, data):
- if not self.connected:
- return True
- if not self.protocol:
- return True
try:
self.protocol.dataReceived(data)
except SystemExit:
def loseConnection(self, reason=None):
self.thread = None
self.closeSocket(reason)
- self.closeProtocol(reason)
def closeSocket(self, reason):
try:
except:
pass
- def closeProtocol(self, reason):
- try:
- if self.connected:
- self.connected = False
- if self.protocol:
- self.protocol.connectionLost(reason)
- except SystemExit:
- raise
- except:
- pass
-
- def getHost(self):
- return self.sock.getsockname()
-
- def getPeer(self):
- return self.addr
-
class SocketListener:
"""A server socket, running listen in a thread.
Accepts connections and runs a thread for each one.
"""
- def __init__(self, factory, backlog=None):
+ def __init__(self, protocol_class, backlog=None):
if backlog is None:
backlog = 5
- self.factory = factory
+ self.protocol_class = protocol_class
self.sock = None
self.backlog = backlog
self.thread = None
self.loseConnection(reason)
def run(self):
- self.factory.doStart()
self.thread = threading.Thread(target=self.main)
- #self.thread.setDaemon(True)
self.thread.start()
def main(self):
return True
def accepted(self, sock, addr):
- protocol = self.factory.buildProtocol(addr)
- if protocol is None:
- self.loseConnection()
- return True
- connection = self.acceptConnection(sock, protocol, addr)
- connection.run()
+ self.acceptConnection(sock, self.protocol_class(), addr).run()
return False
def loseConnection(self, reason=None):
self.thread = None
self.closeSocket(reason)
- self.closeFactory(reason)
def closeSocket(self, reason):
try:
except Exception, ex:
pass
- def closeFactory(self, reason):
- try:
- self.factory.doStop()
- except SystemExit:
- raise
- except:
- pass
class SocketClientConnection:
"""A connection to a server from a client.
self.addr = None
self.connector = connector
self.buffer_n = 1024
- self.connected = False
def createSocket (self):
raise NotImplementedError()
sock = self.createSocket()
sock.connect(self.addr)
self.sock = sock
- self.connected = True
- self.protocol = self.connector.buildProtocol(self.addr)
+ self.protocol = self.connector.protocol_class()
self.protocol.setTransport(self)
except SystemExit:
raise
def loseConnection(self, reason=None):
self.thread = None
self.closeSocket(reason)
- self.closeProtocol(reason)
- self.closeConnector(reason)
def closeSocket(self, reason):
try:
except:
pass
- def closeProtocol(self, reason):
- try:
- if self.connected:
- self.connected = False
- if self.protocol:
- self.protocol.connectionLost(reason)
- except SystemExit:
- raise
- except:
- pass
- self.protocol = None
-
- def closeConnector(self, reason):
- try:
- self.connector.connectionLost(reason)
- except SystemExit:
- raise
- except:
- pass
-
class SocketConnector:
"""A client socket. Connects to a server and runs the client protocol
in a thread.
"""
- def __init__(self, factory):
- self.factoryStarted = False
- self.clientLost = False
- self.clientFailed = False
- self.factory = factory
- self.state = "disconnected"
+ def __init__(self, protocol_class):
+ self.protocol_class = protocol_class
self.transport = None
- def connectTransport(self):
- raise NotImplementedError()
-
def connect(self):
- if self.state != "disconnected":
- raise socket.error(EINVAL, "cannot connect in state " + self.state)
- self.state = "connecting"
- self.clientLost = False
- self.clientFailed = False
- if not self.factoryStarted:
- self.factoryStarted = True
- self.factory.doStart()
- self.factory.startedConnecting(self)
- self.connectTransport()
- self.state = "connected"
-
- def stopConnecting(self):
- if self.state != "connecting":
- return
- self.state = "disconnected"
- self.transport.disconnect()
-
- def buildProtocol(self, addr):
- return self.factory.buildProtocol(addr)
-
- def connectionLost(self, reason=None):
- if not self.clientLost:
- self.clientLost = True
- self.factory.clientConnectionLost(self, reason)
-
- def connectionFailed(self, reason=None):
- if not self.clientFailed:
- self.clientFailed = True
- self.factory.clientConnectionFailed(self, reason)
-
+ pass
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
#============================================================================
# Copyright (C) 2005 Mike Wray <mike.wray@hp.com>
+# Copyright (C) 2005 XenSource Ltd.
#============================================================================
-class Factory:
- """Generic protocol factory.
- """
-
- starts = 0
-
- def __init__(self):
- pass
-
- def doStart(self):
- if self.starts == 0:
- self.startFactory()
- self.starts += 1
-
- def doStop(self):
- if self.starts > 0:
- self.starts -= 1
- else:
- return
- if self.starts == 0:
- self.stopFactory()
-
- def buildProtocol(self, addr):
- return Protocol(self)
-
- def startFactory(self):
- pass
-
- def stopFactory(self):
- pass
-
-class ServerFactory(Factory):
- """Factory for server protocols.
- """
- pass
-
-class ClientFactory(Factory):
- """Factory for client protocols.
- """
-
- def startedConnecting(self, connector):
- pass
-
- def clientConnectionLost(self, connector, reason):
- pass
-
- def clientConnectionFailed(self, connector, reason):
- pass
-
-
class Protocol:
- factory = None
- transport = None
- connected = False
-
- def __init__(self, factory):
- self.factory = factory
+ def __init__(self):
+ self.transport = None
def setTransport(self, transport):
self.transport = transport
- self.connected = bool(transport)
-
- def getTransport(self):
- return self.transport
-
- def connectionMade(self, addr):
- print 'Protocol>connectionMade>', addr
- pass
-
- def connectionLost(self, reason=None):
- print 'Protocol>connectionLost>', reason
- pass
def dataReceived(self, data):
print 'Protocol>dataReceived>'
- pass
def write(self, data):
if self.transport:
return self.transport.read()
else:
return None
-
-class TestClientFactory(ClientFactory):
-
- def buildProtocol(self, addr):
- print 'TestClientFactory>buildProtocol>', addr
- return TestClientProtocol(self)
-
- def startedConnecting(self, connector):
- print 'TestClientFactory>startedConnecting>', connector
-
- def clientConnectionLost(self, connector, reason):
- print 'TestClientFactory>clientConnectionLost>', connector, reason
-
- def clientConnectionFailed(self, connector, reason):
- print 'TestClientFactory>clientConnectionFailed>', connector, reason
-
-class TestClientProtocol(Protocol):
-
- def connectionMade(self, addr):
- print 'TestClientProtocol>connectionMade>', addr
- self.write("hello")
- self.write("there")
-
-class TestServerFactory(Factory):
-
- def buildProtocol(self, addr):
- print 'TestServerFactory>buildProtocol>', addr
- return TestServerProtocol(self)
-
-class TestServerProtocol(Protocol):
-
- def dataReceived(self, data):
- print 'TestServerProtocol>dataReceived>', len(data), data
- #sys.exit(0)
- import os
- os._exit(0)
-
from connection import *
from protocol import *
-class TCPServerConnection(SocketServerConnection):
- pass
-
class TCPListener(SocketListener):
- def __init__(self, port, factory, backlog=None, interface=''):
- SocketListener.__init__(self, factory, backlog=backlog)
+ def __init__(self, port, protocol, backlog=None, interface=''):
+ SocketListener.__init__(self, protocol, backlog=backlog)
self.port = port
self.interface = interface
raise
def acceptConnection(self, sock, protocol, addr):
- return TCPServerConnection(sock, protocol, addr, self)
+ return SocketServerConnection(sock, protocol, addr, self)
class TCPClientConnection(SocketClientConnection):
class TCPConnector(SocketConnector):
- def __init__(self, host, port, factory, timeout=None, bindAddress=None):
- SocketConnector.__init__(self, factory)
+ def __init__(self, host, port, protocol, timeout=None, bindAddress=None):
+ SocketConnector.__init__(self, protocol)
self.host = host
self.port = self.servicePort(port)
self.bindAddress = bindAddress
raise IOError("unknown service: " + ex)
return port
- def connectTransport(self):
+ def connect(self):
self.transport = TCPClientConnection(
self.host, self.port, self.bindAddress, self)
self.transport.connect(self.timeout)
-def listenTCP(port, factory, interface='', backlog=None):
- l = TCPListener(port, factory, interface=interface, backlog=backlog)
+def listenTCP(port, protocol, interface='', backlog=None):
+ l = TCPListener(port, protocol, interface=interface, backlog=backlog)
l.startListening()
return l
-def connectTCP(host, port, factory, timeout=None, bindAddress=None):
- c = TCPConnector(host, port, factory, timeout=timeout, bindAddress=bindAddress)
+def connectTCP(host, port, protocol, timeout=None, bindAddress=None):
+ c = TCPConnector(host, port, protocol, timeout=timeout,
+ bindAddress=bindAddress)
c.connect()
return c
-
-def main(argv):
- host = 'localhost'
- port = 8005
- if argv[1] == "client":
- c = connectTCP(host, port, TestClientFactory())
- print 'client:', c
- else:
- s = listenTCP(port, TestServerFactory())
- print 'server:', s
-
-if __name__ == "__main__":
- main(sys.argv)
-
-
-
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
#============================================================================
# Copyright (C) 2005 Mike Wray <mike.wray@hp.com>
+# Copyright (C) 2005 XenSource Ltd.
#============================================================================
import sys
from connection import *
from protocol import *
-class UnixServerConnection(SocketServerConnection):
- pass
-
class UnixListener(SocketListener):
- def __init__(self, path, factory, backlog=None):
- SocketListener.__init__(self, factory, backlog=backlog)
+ def __init__(self, path, protocol, backlog=None):
+ SocketListener.__init__(self, protocol, backlog=backlog)
self.path = path
def createSocket(self):
return sock
def acceptConnection(self, sock, protocol, addr):
- return UnixServerConnection(sock, protocol, self.path, self)
+ return SocketServerConnection(sock, protocol, self.path, self)
class UnixClientConnection(SocketClientConnection):
class UnixConnector(SocketConnector):
- def __init__(self, path, factory, timeout=None):
- SocketConnector.__init__(self, factory)
+ def __init__(self, path, protocol, timeout=None):
+ SocketConnector.__init__(self, protocol)
self.addr = path
self.timeout = timeout
- def connectTransport(self):
+ def connect(self):
self.transport = UnixClientConnection(self.addr, self)
self.transport.connect(self.timeout)
-def listenUNIX(path, factory, backlog=None):
- l = UnixListener(path, factory, backlog=backlog)
+def listenUNIX(path, protocol, backlog=None):
+ l = UnixListener(path, protocol, backlog=backlog)
l.startListening()
return l
-def connectUNIX(path, factory, timeout=None):
- c = UnixConnector(path, factory, timeout=timeout)
+def connectUNIX(path, protocol, timeout=None):
+ c = UnixConnector(path, protocol, timeout=timeout)
c.connect()
return c
-
-def main(argv):
- path = "/tmp/test-foo"
- if argv[1] == "client":
- c = connectUNIX(path, TestClientFactory())
- print "client:", c
- else:
- s = listenUNIX(path, TestServeractory())
- print "server:", s
-
-if __name__ == "__main__":
- main(sys.argv)
-
from xen.web import protocol, tcp, unix
-from xen.xend import scheduler
from xen.xend import sxp
from xen.xend.XendError import XendError
from xen.xend import XendRoot
"""
def __init__(self):
- #protocol.Protocol.__init__(self)
+ protocol.Protocol.__init__(self)
self.parser = sxp.Parser()
def dataReceived(self, data):
def loseConnection(self):
if self.transport:
self.transport.loseConnection()
- if self.connected:
- scheduler.now(self.connectionLost)
-
- def connectionLost(self, reason=None):
- pass
def send_reply(self, sxpr):
io = StringIO.StringIO()
def opname(self, name):
return 'op_' + name.replace('.', '_')
- def operror(self, name, req):
+ def operror(self, name, _):
raise XendError('Invalid operation: ' +name)
def dispatch(self, req):
op_method = getattr(self, op_method_name, self.operror)
return op_method(op_name, req)
- def op_help(self, name, req):
+ def op_help(self, _1, _2):
def nameop(x):
if x.startswith('op_'):
return x[3:].replace('_', '.')
l = [ nameop(k) for k in dir(self) if k.startswith('op_') ]
return l
- def op_quit(self, name, req):
+ def op_quit(self, _1, _2):
self.loseConnection()
- def op_receive(self, name, req):
+ def op_receive(self, name, _):
if self.transport:
self.send_reply(["ready", name])
self.transport.sock.setblocking(1)
log.error(name + ": no transport")
raise XendError(name + ": no transport")
-class RelocationFactory(protocol.ServerFactory):
- """Asynchronous handler for the relocation server socket.
- """
-
- def __init__(self):
- #protocol.ServerFactory.__init__(self)
- pass
-
- def buildProtocol(self, addr):
- return RelocationProtocol()
def listenRelocation():
- factory = RelocationFactory()
if xroot.get_xend_unix_server():
path = '/var/lib/xend/relocation-socket'
- unix.listenUNIX(path, factory)
+ unix.listenUNIX(path, RelocationProtocol)
if xroot.get_xend_relocation_server():
port = xroot.get_xend_relocation_port()
interface = xroot.get_xend_relocation_address()
- l = tcp.listenTCP(port, factory, interface=interface)
+ l = tcp.listenTCP(port, RelocationProtocol, interface=interface)
l.setCloExec()
def setupRelocation(dst, port):